import { IMSDK, IMMethods } from '@/utils/im';
import type { ConversationItem } from '@openim/client-sdk';

import { defineStore } from 'pinia';
import store from './index';

interface StateType {
  conversationList: ConversationItem[];
  currentConversation: ConversationItem;
  unReadCount: number;
}

const useStore = defineStore('conversation', {
  state: (): StateType => ({
    conversationList: [],
    currentConversation: {} as ConversationItem,
    unReadCount: 0,
  }),
  getters: {
    storeConversationList: state => state.conversationList,
    storeCurrentConversation: state => state.currentConversation,
    storeUnReadCount: state => state.unReadCount,
  },
  actions: {
    async getConversationListFromReq(isScrollLoad = false): Promise<boolean> {
      try {
        const { data } = await IMSDK.asyncApi(IMMethods.GetConversationListSplit, IMSDK.uuid(), {
          offset: isScrollLoad ? this.conversationList.length : 0,
          count: 20,
        });

        const cves = data;
        this.conversationList = [...(isScrollLoad ? this.conversationList : []), ...cves];
        return cves.length === 20;
      } catch (error) {
        console.error(error);
        return false;
      }
    },
    async getUnReadCountFromReq() {
      const { data } = await IMSDK.asyncApi(IMMethods.GetTotalUnreadMsgCount, IMSDK.uuid());
      this.unReadCount = data;
    },
    updateUnReadCount(data: number) {
      this.unReadCount = data;
    },
    updateCurrentConversation(item: ConversationItem) {
      this.currentConversation = { ...item };
    },
    updateConversationList(list: ConversationItem[]) {
      this.conversationList = [...list];
    },
    clearConversationStore() {
      this.conversationList = [];
      this.currentConversation = {} as ConversationItem;
      this.unReadCount = 0;
    },
  },
});

export default function useConversationStore() {
  return useStore(store);
}
